package com.fengye.security.jwt;

import com.fengye.security.jwt.process.*;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.core.annotation.Order;
import org.springframework.security.config.annotation.ObjectPostProcessor;
import org.springframework.security.config.annotation.authentication.builders.AuthenticationManagerBuilder;
import org.springframework.security.config.annotation.method.configuration.EnableGlobalMethodSecurity;
import org.springframework.security.config.annotation.web.builders.HttpSecurity;
import org.springframework.security.config.annotation.web.builders.WebSecurity;
import org.springframework.security.config.annotation.web.configuration.EnableWebSecurity;
import org.springframework.security.config.annotation.web.configuration.WebSecurityConfigurerAdapter;
import org.springframework.security.config.http.SessionCreationPolicy;
import org.springframework.security.crypto.password.PasswordEncoder;
import org.springframework.security.web.access.intercept.FilterSecurityInterceptor;
import org.springframework.security.web.authentication.UsernamePasswordAuthenticationFilter;

import javax.annotation.Resource;

/**
 * Spring Security 配置类
 */
@Configuration(value = "jwtSpringWebSecurityConfig")
@EnableWebSecurity
@EnableGlobalMethodSecurity(prePostEnabled = true)
@Order(2)
public class JwtSpringWebSecurityConfig extends WebSecurityConfigurerAdapter {

    @Resource
    private JwtUserDetailsService jwtUserDetailsService;

    @Resource
    private PasswordEncoder passwordEncoder;

    /**
     * 认证失败处理器
     */
    @Resource
    private JwtAuthenticationFailureHandler jwtAuthenticationFailureHandler;

    /**
     * 认证成功处理器
     */
    @Resource
    private JwtAuthenticationSuccessHandler jwtAuthenticationSuccessHandler;

    /**
     * 未登录访问登录资源,401
     */
    @Resource
    private JwtAuthenticationEntryPoint jwtAuthenticationEntryPoint;

    /**
     * 一登录,但是无权限该资源 403
     */
    @Resource
    private JwtAccessDeniedHandler jwtAccessDeniedHandler;

    @Resource
    private JwtFilterInvocationSecurityMetadataSource jwtFilterInvocationSecurityMetadataSource;

    @Resource
    private JwtAccessDecisionManager jwtAccessDecisionManager;


    /**
     * 使用自定义验证实现器
     *
     * @return 自定义验证实现器
     */
    @Bean
    public JwtAuthenticationProvider jwtAuthenticationProvider(JwtUserDetailsService jwtUserDetailsService, PasswordEncoder passwordEncoder) {
        return new JwtAuthenticationProvider(jwtUserDetailsService, passwordEncoder);
    }

    @Override
    protected void configure(HttpSecurity http) throws Exception {
        // 登陆验证信息
        http.antMatcher("/jwt/**")
                .authenticationProvider(jwtAuthenticationProvider(jwtUserDetailsService, passwordEncoder))
                .authorizeRequests()
                .withObjectPostProcessor(new ObjectPostProcessor<FilterSecurityInterceptor>() {
                    @Override
                    public <O extends FilterSecurityInterceptor> O postProcess(O object) {
                        object.setSecurityMetadataSource(jwtFilterInvocationSecurityMetadataSource);
                        object.setAccessDecisionManager(jwtAccessDecisionManager);
                        return object;
                    }
                })
                .anyRequest().authenticated()
                .and().cors()
                .and().sessionManagement().sessionCreationPolicy(SessionCreationPolicy.STATELESS) // 禁用session
                .and().csrf().disable();

        // 允许跨域访问
        // http.cors();

        // http.

        // 自定义登陆拦截器
        JwtLoginFilter jwtLoginFilter = new JwtLoginFilter();
        jwtLoginFilter.setAuthenticationManager(authenticationManagerBean());
        jwtLoginFilter.setAuthenticationSuccessHandler(jwtAuthenticationSuccessHandler);
        jwtLoginFilter.setAuthenticationFailureHandler(jwtAuthenticationFailureHandler);

        /*
         * 验证token,访问资源
         */
        JwtTokenFilter jwtTokenFilter = new JwtTokenFilter(jwtUserDetailsService);
        // jwt 拦截器配置
        http.addFilterAt(jwtLoginFilter, UsernamePasswordAuthenticationFilter.class) // 添加拦截器
                .addFilterAfter(jwtTokenFilter, JwtLoginFilter.class);
        // 异常处理
        http.exceptionHandling()
                // 未认证状态下访问需要访问权限的资源
                .authenticationEntryPoint(jwtAuthenticationEntryPoint)
                // 以认证用户,但是权限不足时
                .accessDeniedHandler(jwtAccessDeniedHandler);

    }

    @Override
    protected void configure(AuthenticationManagerBuilder auth) throws Exception {
        super.configure(auth);
    }

    @Override
    public void configure(WebSecurity web) {
        web.ignoring()
                .antMatchers("/swagger-ui.html")
                .antMatchers("/doc.html")
                .antMatchers("/swagger-ui/**")
                .antMatchers("/swagger-resources/**")
                .antMatchers("/v2/api-docs")
                .antMatchers("/v3/api-docs")
                .antMatchers("/webjars/**")
                .mvcMatchers("/static/**");
    }


}